package com.zxinlee.order.service.impl;

import com.zxinlee.order.entity.Order;
import com.zxinlee.order.feign.AccountClient;
import com.zxinlee.order.feign.EasyIdClient;
import com.zxinlee.order.feign.StorageClient;
import com.zxinlee.order.mapper.OrderMapper;
import com.zxinlee.order.service.OrderService;
import com.zxinlee.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderTccAction orderTccAction;

    @Autowired
    private EasyIdClient easyIdClient;

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private OrderMapper orderMapper;

    @GlobalTransactional//启动全局事务
    @Override
    public void create(Order order) {

        // TODO : 从全局唯一id发号器获得id，这里暂时随机产生一个 orderId
        //Long orderId = Long.valueOf(new Random().nextInt(Integer.MAX_VALUE));
        Long orderId = Long.valueOf(easyIdClient.nextId("order_business"));
        order.setId(orderId);

        /**
         * orderTccAction 实例,是动态代理对象,
         * 用AOP添加切面代码,创建的上下文对象,然后传入原始方法
         * 所以可以给null值
         */
        //不直接完成业务数据操作,而是调用Tcc的第一阶段业务方法 -- 冻结调用
        //orderMapper.create(order);
        orderTccAction.prepare(
                null,
                order.getId(),
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney());

        // TODO: 远程调用storage，修改库存
        storageClient.decrease(order.getProductId(),order.getCount());

        // TODO: 远程调用account，修改账户余额
        accountClient.decrease(order.getUserId(),order.getMoney());

    }
}
